import { defineStore } from 'pinia'
import { referenceIndex, logRecord } from '@/api/calc'
import { decryptData } from '@/utils/calc'
import { getURL, getBrowserInfo } from '@/utils/helper'
import { useGlobeStore } from '@/stores'

export const useUserStore = defineStore('user', {
  persist: {
    key: 'user',
    pick: ['i', 'info', 'spaceMark','decryptedStrs'],
  },
  state: () => ({
    i: '', // 问彩用户的uuid 等同于分享的token
    info: {}, // 用户信息
    articleLink: 'https://mp.weixin.qq.com/s/hgirhOLcVMbf-7IpzIHYKQ', // 解密用
    shopUuid: [], // 样板间店铺ID
    channelWeb: getBrowserInfo(),
    homeAdUrl: '',
    spaceMark: '',
    decryptedStrs: '',
  }),
  getters: {
    shopName: (state) => state.info.shop_name || state.info.member_list_username,
  },
  actions: {
    initConfig({ shopUuid, articleLink, homeAdUrl }){
      this.shopUuid = shopUuid;
      this.articleLink = articleLink;
      this.homeAdUrl = homeAdUrl;
    },
    updateShareInfo(){
      if (this.shopName){
        const title = `${this.shopName}的赛事分析助手`;
        document.title = title
        var metaTit = document.getElementById('meta-title');
        var metaTit2 = document.getElementById('meta-title2');
        if (metaTit){
          metaTit.setAttribute('content', title);
        }
        if (metaTit2) {
          metaTit2.setAttribute('content', title);
        }
      }
      if (this.info.shop_photo){
        var metaImg = document.getElementById('meta-image');
        var metaImg2 = document.getElementById('meta-image2');
        var shareImg = document.getElementById('shareImg');
        const globe = useGlobeStore();
        const cover = `${globe.staticDomain}/${this.info.shop_photo}_s300`;
        if (shareImg){
          shareImg.src = cover;
        }
        if (metaImg) {
          metaImg.setAttribute('content', cover);
        }
        if (metaImg2) {
          metaImg2.setAttribute('content', cover);
        }
      }
    },
    async queryReference() {
      try {
        const res = await referenceIndex({ i: this.i })
        if (res) {
          // 密文和iv间隔符
          const splitArr = this.articleLink.split('/')
          this.spaceMark = splitArr.slice(-1)[0]
          const enAry = res.split(this.spaceMark)
          // 通过索引，得到内参中用户信息
          this.info = decryptData({ da: enAry[2], de: enAry[1] })
          // 通过索引，得到内参中插入的广告词
          this.decryptedStrs = decryptData({ da: enAry[0], de: enAry[1] })
          this.updateShareInfo()
        }
        return;
      } catch (error) {
        throw error;
      }
    },
    async getUserInfo(i){
      if (this.i && this.i == i && this.spaceMark) return;
      if(i) this.i = i;
      await this.queryReference();
    },
    log({ type, action, opt_label, target_url, data_id }){
      if (!this.i) return;
      const globe = useGlobeStore()
      logRecord({
        i: this.i,
        cid: globe.cid,
        page_url: getURL(),
        channel: this.channelWeb,
        type, // pageview、event
        category: 'shop_helper', // shop_helper
        action, // click、page
        opt_label, // 中文名称
        target_url,
        data_id
      });
    }
  }
})
